package cn.codeartist.springboot.component.aop;

import cn.codeartist.springboot.component.util.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求日志切片
 * 暂时只拦截 {@code @RestController} 注解，不兼容 {@code @Controller + @ResponseBody} 组合注解，如果需求可以添加该切点
 *
 * @author 艾江南
 * @date 2019/3/30
 */
@Aspect
public class RequestLogAspect {

    final private Logger logger = LoggerFactory.getLogger(RequestLogAspect.class);

    /**
     * Use around advice to handle log
     */
    @Around("@within(restController)")
    public Object doAround(ProceedingJoinPoint joinPoint, RestController restController) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return joinPoint.proceed();
        }
        HttpServletRequest request = attributes.getRequest();
        String query = request.getQueryString();
        Object result = null;
        long start = System.currentTimeMillis();
        try {
            result = joinPoint.proceed();
        } finally {
            long end = System.currentTimeMillis();
            logger.info("HTTP {} {} ,cost:{}ms, param:{}, result:{}, header:{}", request.getMethod(),
                    request.getRequestURL() + (StringUtils.isEmpty(query) ? "" : "?" + query),
                    end - start,
                    JSON.toJSONString(parseParams(request, joinPoint.getArgs(), (MethodSignature) joinPoint.getSignature())),
                    JSON.toJSONString(result),
                    JSON.toJSONString(parseHeaders(request)));
        }
        return result;
    }

    /**
     * Parse HTTP headers
     */
    private Map<String, String> parseHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>(16);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String header = headerNames.nextElement();
            headers.put(header, request.getHeader(header));
        }
        return headers;
    }

    /**
     * Parse request parameters
     */
    private Map<String, Object> parseParams(HttpServletRequest request, Object[] args, MethodSignature signature) {
        Map<String, Object> params = new HashMap<>(16);
        if (request.getContentType() != null && MediaType.APPLICATION_JSON_UTF8_VALUE.contains(request.getContentType())) {
            String[] names = signature.getParameterNames();
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof ServletRequest ||
                        args[i] instanceof ServletResponse ||
                        args[i] instanceof MultipartFile) {
                    continue;
                }
                params.put(names[i], args[i]);
            }
        } else {
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String param = parameterNames.nextElement();
                params.put(param, request.getParameter(param));
            }
        }
        return params;
    }
}
